package org.example.eight;

import com.rabbitmq.client.*;
import org.example.utils.RabbitMqUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 正常消费者
 */
public class NormalConsumer01 {
    //正常交换机
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机
    public static final String DEAD_EXCHANGE = "dead_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        //正常队列
        String normalQueue = "normalQueue";
        //死信队列
        String deadQueue = "deadQueue";
        Channel channel = RabbitMqUtil.getChannel();
        //声明交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT);
        //声明正常队列
        Map<String,Object> arguments = new HashMap<>();
        //过期时间 10s,这里可以设置ttl,在生产者那里也可以
//        arguments.put("x-message-ttl",10000);
        //正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key","lisi");
        //设置正常队列的长度限制,  参数不变可以重新启动,参数变了就要先删队列才能启动
//        arguments.put("x-max-length",6);

        channel.queueDeclare(normalQueue,false,false,false,arguments);

        //声明死信队列
        channel.queueDeclare(deadQueue,false,false,false,null);

        //绑定普通队列
        channel.queueBind(normalQueue,NORMAL_EXCHANGE,"zhangsan");
        //绑定死信队列
        channel.queueBind(deadQueue,DEAD_EXCHANGE,"lisi");

        //普通队列消费
        DeliverCallback deliverCallback = (String message, Delivery delivery) -> {
            String meg = new String(delivery.getBody());
            if (meg.equals("info5")){
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(),false);
                System.out.println("消息拒收了: " + meg);
            } else {
                System.out.println(meg+" :消息接收到了");
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
            }
        };
        CancelCallback cancelCallback = message -> {
            System.out.println("消息取消了");
            System.out.println(message);
        };
        channel.basicConsume(normalQueue,false,deliverCallback,cancelCallback);
    }
}
